// 解决副作用函数和key无关联问题
let activeEffect
const data = {text: 'hello'}
const bucket = new WeakMap()

// 收集依赖
function track (target, key) {
  let depsMap = bucket.get(target)
  if (!depsMap) {
    bucket.set(target, depsMap = new Map())
  }
  let deps = depsMap.get(key)
  if (!deps) {
    depsMap.set(key, deps = new Set())
  }
  if (activeEffect) {
    deps.add(activeEffect)
  }
}
// 触发事件
function trigger (target, key) {
  const depsMap = bucket.get(target)
  if (!depsMap) return
  const deps = depsMap.get(key)
  deps && deps.forEach(effect => effect())
}
const obj = new Proxy(data, {
  get(target, key) {
    track(target, key)
    return target[key]
  },
  set(target, key, value) {
    target[key] = value
    trigger(target, key)
  }
})

function effect (fn) {
  activeEffect = fn
  fn()
}

effect(() => {
  console.log(obj.text, 'obj.text的值')
})

obj.text = '123'

setTimeout(() => {
  obj.text = 444
}, 1000)

/**
 * 解析:
 * 这样, effect就和key之间建立联系, 也就不存在修改任何key, 哪怕不存在
 * 也会动到副作用函数了
 * 缺陷:
 * 如下代码, 哪怕ok变成false, obj.text已经不再需要监听了, 最后设为444的时候
 * 还是会触发副作用函数
 * effect(() => {
    const value = obj.ok ? obj.text : '123123'
    console.log(value, 'value???')
  })

  obj.text = '123'
  obj.ok = false
  setTimeout(() => {
    obj.text = 444 // 还会触发函数
  }, 1000)
 */